<?php

namespace System\Configure\Adapter;

use System\Configure\AdapterAbstract;
use System\Configure\Exception\ParserIniException;

/**
 * INI配置文件解析类
 *
 * @package Dream
 * @subpackage Ini
 * @namespace System\Configure\Adapter
 * @author lewis (lewisld@yeah.net)
 */
class Ini extends AdapterAbstract
{
    /**
     * INI配置文件解析后的数组
     *
     * @static
     * @access protected
     * @var array
     */
    protected static $data = [];

    /**
     * 解析INI配置文件到数组
     *
     * @static
     * @access public
     * @param string $path INI配置文件路径
     * @return array 返回INI配置项数组
     * @throws ParseIniException 解析INI配置文件到数组异常
     */
    public static function parser($path)
    {
        $data = @parse_ini_file($path, true);
        if (! $data) {
            $error = error_get_last();
            $error['inifile'] = $path;
            $error['message'] = 'system.error.conf.parser.ini';
            throw new ParserIniException($error);
        }
        foreach ($data as $namespace => $properties) {
            self::set($namespace, $properties);
        }
        unset($data, $namespace, $properties);
        return self::$data;
    }

    /**
     * 设置数组
     *
     * @access protected
     * @param string $key 数组键名，多个键名之间以“.”分隔
     * @param mixed $value 数组值
     * @return void 没有返回值
     */
    protected static function set($key, $value)
    {
        $root = &self::$data;
        foreach (explode('.', $key) as $part) {
            if (!isset($root[$part])) {
                $root[$part] = [];
            }
            $root = &$root[$part];
        }
        $root = $value;
        unset($root, $part);
    }
}